package xdu.lz.stage2_design_pattern.chapter1_volatie.volitale;


/**
 * volatile不能保证原子性
 * 1)内存可见性
 * 2)防止重排序--happens-before原则
 */
public class VolatileTest2 {
    private static volatile int initValue = 0;
//    private static int initValue = 0;
    private static final int MAX_VALUE = 200;

    public static void main(String[] args) {
        new Thread(()->{

            //如果是写操作，那么会每次都更新到主内存,volatile不会保证线程安全性
            while (initValue < MAX_VALUE){
                System.out.println(Thread.currentThread().getName()+"update the value to "+
                        (++initValue));
                try {
                    Thread.sleep(10L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"write -thread1").start();

        new Thread(()->{
            while (initValue < MAX_VALUE){
                System.out.println(Thread.currentThread().getName()+"update the value to "+
                        (++initValue));
                try {
                    Thread.sleep(10L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"write -thread2").start();

    }
}
